package com.ccl.iot.huiju;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

import com.ccl.iot.R;
import com.ccl.iot.dialogs.UserRegisterDialog;
import com.ccl.iot.template.ActivityDialog;

public class LoginDialog extends ActivityDialog {
    public static final String KEXTRA_NAME_FORCE_LOGIN = "ForceLogin";

    public interface LoginListener extends ActivityDialog.DialogInterface, UserRegisterDialog.UserRegisterListener {
         void onLogin(String aUserName, String aPassword);
    }

    private static volatile boolean gShowing = false;

    public static void Show(Context aContext, LoginListener aLoginListener, boolean aForceLogin) {
        if (gShowing == false) {
            gShowing = true;

            Bundle tBundle = ActivityDialog.ObtainBundle(false, false);

            tBundle.putBoolean(KEXTRA_NAME_FORCE_LOGIN, aForceLogin);

            ActivityDialog.Show(aContext, LoginDialog.class, tBundle, aLoginListener);

        }
    }


    private LoginListener iLoginListener = null;
    private boolean iForceLogin = false;

    private EditText iUser = null;
    private EditText iPassword = null;

    private Button iLogon = null;

    private AlertDialog.Builder iNoLoginDialog = null;
    private UserRegisterDialog iRegisterDialog = null;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        initialize();

        initializeLayout();
    }

    private void initialize() {

        //start to UserManager.iLoginListener
        iLoginListener = (LoginListener) super.getDialogInterface();

        iForceLogin = this.getIntent().getBooleanExtra(KEXTRA_NAME_FORCE_LOGIN, iForceLogin);
    }

    private void initializeLayout() {
        this.setTitle(R.string.user_Login);
        this.setContentView(R.layout.login_dialog);

        iUser = (EditText) this.findViewById(R.id.login_account);
        iPassword = (EditText) this.findViewById(R.id.login_password);

        iLogon = (Button) this.findViewById(R.id.login_logon);

        handleInputEvent();

        handleButtonEvent();

        hideBottomUIMenu();
    }

    private int getTextLength(TextView aText) {
        if (aText != null) {
            return aText.getText().length();
        }

        return 0;
    }

    private boolean isInfoValid() {
        return getTextLength(iUser) > 0 && getTextLength(iPassword) > 0;
    }

    private void handleUsefulInfoChange(EditText aInfo) {
        if (aInfo != null) {
            aInfo.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start,
                                              int count, int after) {
                }

                @Override
                public void onTextChanged(CharSequence s, int start,
                                          int before, int count) {
                }

                @Override
                public void afterTextChanged(Editable s) {
                    iLogon.setEnabled(isInfoValid());
                }
            });
        }
    }

    private void handleInputEvent() {
        if (iUser != null) {
            //请求获取焦点
//            iUser.requestFocus();

            //打开输入法
//            Window.ShowInputDialog(getContext());

            //监听userName是否有效,如无效则登录按钮无效
            handleUsefulInfoChange(iUser);
        }

        if (iPassword != null) {
            //监听userPwd是否有效,如无效则登录按钮无效
            handleUsefulInfoChange(iPassword);

            //当按下enter键且userName和userPwd都有效时,自动登录
            iPassword.setOnEditorActionListener(new OnEditorActionListener() {
                @Override
                public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                    if (actionId == EditorInfo.IME_ACTION_DONE || (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
                        if (iUser != null && iUser.getText().length() > 0) {
                            login();
                        }
                    }

                    return false;
                }
            });
            //iPassword.setText("123");
        }
    }

    private void login() {
        if (isInfoValid()) {
            if (iLoginListener != null) {
                iLoginListener.onLogin(iUser.getText().toString(), iPassword.getText().toString());
            }
        }
    }

    private void handleButtonEvent() {

        if (iLogon != null) {
            iLogon.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    login();
                }
            });
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onStop() {
        if (iRegisterDialog != null && iRegisterDialog.isShowing()) {
            iRegisterDialog.dismiss();

            iRegisterDialog = null;
        }

        super.onStop();

        gShowing = false;
    }


    public Dialog getRegisterDialog() {
        return iRegisterDialog;
    }


    /**
     * 隐藏虚拟按键，并且全屏
     */
    public void hideBottomUIMenu() {

        //隐藏虚拟按键，并且全屏
        if (Build.VERSION.SDK_INT > 11 && Build.VERSION.SDK_INT < 19) { // lower api
            View v = getWindow().getDecorView();
            v.setSystemUiVisibility(View.GONE);
        } else if (Build.VERSION.SDK_INT >= 19) {
            //for new api versions.
            View decorView = getWindow().getDecorView();
            int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY | View.SYSTEM_UI_FLAG_FULLSCREEN;
            decorView.setSystemUiVisibility(uiOptions);
        }

    }
}
